import sys
import os
import pandas as pd
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QVBoxLayout, QFileDialog, QComboBox, QRadioButton, QHBoxLayout, QMessageBox

class ExcelSplitterGUI(QWidget):
    def __init__(self):
        super().__init__()

        self.init_ui()

    def init_ui(self):
        self.setWindowTitle('Excel 行拆分工具')
        self.setGeometry(300, 300, 400, 250)  # 设置窗口大小和位置

        self.label = QLabel('选择要拆分的Excel文件:')
        self.select_button = QPushButton('选择文件', self)
        self.select_button.clicked.connect(self.select_file)

        self.field_label = QLabel('选择用作文件名的字段:')
        self.field_combobox = QComboBox(self)

        self.output_label = QLabel('输出路径选项:')
        self.default_radio = QRadioButton('默认路径', self)
        self.custom_radio = QRadioButton('自定义路径', self)
        self.custom_radio.toggled.connect(self.toggle_custom_path)

        self.output_button = QPushButton('选择路径', self)
        self.output_button.clicked.connect(self.select_output_path)

        self.split_button = QPushButton('拆分并保存', self)
        self.split_button.clicked.connect(self.split_and_save)

        vbox = QVBoxLayout(self)
        vbox.addWidget(self.label)
        vbox.addWidget(self.select_button)
        vbox.addWidget(self.field_label)
        vbox.addWidget(self.field_combobox)
        vbox.addWidget(self.output_label)
        vbox.addWidget(self.default_radio)
        vbox.addWidget(self.custom_radio)
        vbox.addWidget(self.output_button)
        vbox.addWidget(self.split_button)

        self.output_path = os.path.join(os.path.expanduser("~"), 'Desktop')  # Set default path to desktop
        self.custom_path_enabled = False  # Variable to track whether custom path is enabled

    def select_file(self):
        file_path, _ = QFileDialog.getOpenFileName(self, '选择Excel文件', '', 'Excel 文件 (*.xlsx *.xls)')
        if file_path:
            self.input_file_path = file_path
            self.label.setText(f'选择的文件: {file_path}')

            # 读取Excel文件的列名，添加到字段选择框
            df = pd.read_excel(file_path)
            self.field_combobox.addItems(df.columns)

    def toggle_custom_path(self):
        self.custom_path_enabled = self.custom_radio.isChecked()

    def select_output_path(self):
        if self.custom_path_enabled:
            directory = QFileDialog.getExistingDirectory(self, '选择输出路径', '')
            if directory:
                self.output_path = directory
        else:
            self.output_path = os.path.join(os.path.expanduser("~"), 'Desktop')

    def split_and_save(self):
        try:
            input_file_path = self.input_file_path
            selected_field = self.field_combobox.currentText()
        except AttributeError:
            self.label.setText('请先选择要拆分的Excel文件和字段')
            return

        # 读取Excel文件
        df = pd.read_excel(input_file_path)

        # 遍历每行数据
        for index, row in df.iterrows():
            # 获取当前行字段的值，用作文件名
            file_name = str(row[selected_field])

            # 创建新的Excel文件
            output_file = os.path.join(self.output_path, f'{file_name}.xlsx')

            # 将当前行数据写入新的Excel文件
            row_df = pd.DataFrame([row], columns=df.columns)
            row_df.to_excel(output_file, index=False)

        self.label.setText('拆分完成！')
        QMessageBox.information(self, '完成', '拆分完成！', QMessageBox.Ok)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = ExcelSplitterGUI()
    ex.show()
    sys.exit(app.exec_())
